# coding=UTF-8
from flask import Flask, render_template, url_for, redirect
from flask import request
import os, time
from PIL import Image, ImageDraw, ImageFont

root_dir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)

root = "root"
suffix = "png"

def gen_img(size=None):
    if size is None:
        size = 400
        #生成大小为400x400RGBA是四通道图像，RGB表示R，G，B三通道，A表示Alpha的色彩空間
    image = Image.new(mode='RGBA', size=(400, 400), color=(255, 55, 55))
    # ImageDraw.Draw 简单平面绘图
    draw_table = ImageDraw.Draw(im=image)
    # 直接显示图片
    image.show()

def pic_open(filepath):
    #图片打开与显示
    image = Image.open(filepath)
    return image

def get_size(image):
    #获取图像的宽和高
    width, height = image.size
    return width,height

def pic_text(filepath,size,text,setFont,fillColor,filename,direction=None):
    print(filepath,size,text,setFont,fillColor)
    #打开图片
    image=pic_open(filepath)
    #新建绘图对象
    draw = ImageDraw.Draw(image)
    #显示图片
    # image.show()
    draw.text(size ,text,font=setFont,fill=fillColor,direction=None)
    # image.show()
    #保存
    pic_save(image,filename)

def pic_save(image,filename):
    #保存
    image.save(filename)

@app.route('/', methods=['GET', 'POST'])
def index():
    name = request.args.get("name", root)
    image_url = url_for('static', filename=name+"."+suffix)
    return render_template('index.html', image_url=image_url)

def do_make(name):
    if name == root:
        return
    #** ImageFont模块**
    #选择文字字体和大小
    setFont = ImageFont.truetype('songti.TTF', 48)
    #设置文字颜色
    fillColor = "#000000"   #蓝色
    text=name
    n = len(name)
    size=(350,1000)
    filepath="static/%s.%s" % (root, suffix)
    filename="static/%s.%s" % (name, suffix)
    if os.path.exists(filename):
        os.remove(filename)
    #打开图片
    image=pic_open(filepath)
    #添加文字
    pic_text(filepath,size,text,setFont,fillColor,filename,direction=None)

@app.route('/make', methods=['POST', 'GET'])
def make():

    if request.method == 'POST':
        name = request.form['name']
        if not name:
            return redirect(url_for('index'))
        do_make(name)
        return redirect(url_for('index', name=name))
    return redirect(url_for('index'))


if __name__ == '__main__':
    app.run(
        host='0.0.0.0',
        port= 80,
        debug=False)